package com.itHaipeng.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.SQLException;

/**
 * 和事物管理相关的工具类，它包含了开启事物，提交事物，回滚事物和释放链接
 *
 * */
@Service(value = "transactionManager")
public class TransactionManager {
    @Autowired
    private ConnectionUtil connectionUtil;
    //开启事物
    public void openTransaction(){
        try {
            connectionUtil.getThreadConnection().setAutoCommit(false);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
    //提交事物
    public void commitTransaction(){
        try {
            connectionUtil.getThreadConnection().commit();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
    //回滚事物
    public void rollbackTransaction(){
        try {
            connectionUtil.getThreadConnection().rollback();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
    //释放链接
    public void closeTransaction(){
        try {
            connectionUtil.getThreadConnection().close();//还回连接池中，线程还回线程池中
            connectionUtil.removeConnection();//解绑
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
